package model

import (
	"errors"
	"gitee.com/jikey/elk-blog/pkg/hash"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"github.com/sirupsen/logrus"
	"os/user"
)

type User struct {
	BaseModel
	Username    string `gorm:"column:username;type:varchar(20);not null " json:"username" validate:"required,min=4,max=12" label:"用户名"`
	Password    string `gorm:"type:varchar(500);not null" json:"-" validate:"required,min=6,max=120" label:"密码"`
	Sex         int    `gorm:"column:sex;type:tinyint(2)" json:"sex"`
	Nickname    string `gorm:"column:nickname;type:varchar(100)" json:"nickname"`
	Avatar      string `gorm:"column:avatar;type:varchar(200)" json:"avatar"`
	Description string `gorm:"column:description;type:varchar(100)" json:"description"`
	Loginip     string `gorm:"column:loginip;type:varchar(20)" json:"loginip"`
	Logintime   string `gorm:"column:logintime;type:varchar(50)" json:"logintime"`
	Verify      string `gorm:"column:verify;type:varchar(32)" json:"verify"`
	Email       string `gorm:"column:email;type:varchar(50)" json:"email"`
	Isadmin     int    `gorm:"column:isadmin;type:tinyint(1)" json:"isadmin"`
	Status      int    `gorm:"column:status;type:tinyint(1)" json:"status"`
	Address     string `gorm:"column:address;type:varchar(255)" json:"address"`
}

/**
校验用户名
*/
func (u *User) checkName() (err error) {
	nameLen := len(u.Username)

	if !(nameLen < 12) {
		err = errors.New("用户名长度必须是4到12位")
		return
	}
	return
}

// BeforeCreate 密码加密&权限控制
func (u *User) BeforeCreate(scope *gorm.Scope) (err error) {
	err = u.BaseModel.BeforeCreate(scope)
	if err != nil {
		return err
	}

	u.Password = hash.BcryptHash(u.Password)
	return nil
}

func (u *User) BeforeUpdate(scope *gorm.Scope) (err error) {
	err = u.BaseModel.BeforeUpdate(scope)
	if err != nil {
		return err
	}

	u.Password = hash.BcryptHash(u.Password)
	return nil
}

// CurrentUser 从 gin.context 中获取当前登录用户
func CurrentUser(c *gin.Context) user.User {
	userModel, ok := c.MustGet("current_user").(user.User)

	if !ok {
		logrus.Error(errors.New("无法获取用户"))
		return user.User{}
	}

	return userModel
}

// CurrentUserID 从 gin.context 中获取当前登录用户 ID
func CurrentUserID(c *gin.Context) string {
	return c.GetString("current_user_id")
}
